import {defineStore} from "pinia";
import service from "@/utils/useRequest";
import {type FormInstance, type FormRules} from "element-plus";
import {showModal, toast} from "@/utils/useLayer";
import {Random} from "mockjs";
import dayjs from "dayjs";
import {imitatejs} from 'imitatejs'

export const useListStore = defineStore(
    "list",
    () => {
        // 用户信息
        const userInfo = ref([])
        const userAvatarSrcList = ref([])
        const preAvatarSrcList = ref([])
        const isLoading = ref(false)

        // 新增
        const dialogVisible = ref(false)
        const addBtnLoading = ref(false)
        const isFullscreen = ref(false)
        const tooltipVisible = ref(false)
        const addFormRef = ref<FormInstance>()
        const addFormModel = ref({
            name: '',
            address: '',
            create_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
        })
        const addFormRules = ref<FormRules<typeof addFormModel>>({
            name: [
                {
                    required: true, message: '请输入用户名', trigger: 'blur'
                },
            ],
            address: [
                {
                    required: true, message: '请输入地址', trigger: 'blur'
                }
            ],
            create_time: [
                {
                    type: 'date', required: true, message: '请输入日期', trigger: 'blur'
                }
            ]
        })

        // 编辑
        const editDialogVisible = ref(false);
        const editIsFullscreen = ref(false);
        const editTooltipVisible = ref(false);
        const editFormRef = ref<FormInstance>()
        const editFormModel = ref({
            name: "",
            avatar: "",
            address: "",
            create_time: "",
        })
        const editFormRules = ref<FormRules<typeof editFormModel>>({
            name: [
                {required: true, message: '请输入用户名', trigger: 'blur'},
            ],
            avatar: [
                {required: true, message: '请输入头像地址', trigger: 'blur'},
            ],
            address: [
                {required: true, message: '请输入地址', trigger: 'blur'},
            ],
            create_time: [
                {required: true, message: '请输入创建时间', trigger: 'blur'},
            ]
        })
        const editBtnLoading = ref(false)
        const updateTime = ref('')
        const rawData = ref({})

        // 搜索
        const searchFormModel = ref({
            keyword: '',
            phone: '',
        })

        // 分页
        const pageSize = 10
        const currentPage = ref(1)
        const totalCount = ref(0)
        const currentTableData = ref([])

        // 获取数据
        const getUserInfo = async () => {

            isLoading.value = true

            const res = await service.request({
                url: '/userList',
                method: 'GET'
            })

            if (res.data.status === 200) {
                userInfo.value = res.data.data.map(item => {
                    userAvatarSrcList.value.push(item.avatar)

                    const preAvatarSrc = item.avatar.replace('50x50', '200x200')
                    preAvatarSrcList.value.push(preAvatarSrc)

                    item.phone = imitatejs().phone()
                    return item
                })

                isLoading.value = false

                // 记录索引最大值  追加数据
                const maxIndexById = userInfo.value.reduce((prev, current) => (prev.id > current.id) ? prev.id : current.id)
                localStorage.setItem('userMaxIndex', JSON.stringify(maxIndexById))
            }
        }

        // 新增
        const handleAddSubmit = (FormEl: FormInstance | undefined) => {
            if (!FormEl) return;
            FormEl.validate(async (valid: boolean) => {
                if (!valid) return;
                else {
                    //
                    const maxIndex = JSON.parse(localStorage.getItem('userMaxIndex') || 0)
                    const newUserData = {
                        id: maxIndex + 1,
                        age: Random.natural(18, 60),
                        gender: Random.pick(['男', '女']),
                        status: true,
                        avatar: Random.image('50x50', Random.color(), Random.color(), 'png', Random.first()),
                        update_time: Random.now('A HH:mm:ss'),
                        token: Random.guid(),
                        ...addFormModel.value
                    }
                    addBtnLoading.value = true

                    const res = await service.request({
                        url: '/addUser',
                        method: 'POST',
                        data: newUserData
                    })

                    if (res.status === 200) {
                        dialogVisible.value = false

                        await getUserInfo()

                        toast(res.data.message)
                        // 添加后重置表单
                        addFormModel.value = {
                            name: '',
                            address: '',
                            create_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
                        }
                    } else {
                        toast(res.data.message, 'error')
                    }
                }
            }).finally(() => {
                addBtnLoading.value = false
            })
        }

        // 回显编辑表单数据
        const echoEditData = (row) => {
            editDialogVisible.value = true
            // 浅拷贝
            editFormModel.value = {...row}
            rawData.value = Object.assign({}, row)
        }

        // 编辑
        const handleEditSubmit = async (FormEl: FormInstance | undefined, editForm: typeof editFormModel) => {
            if (!FormEl) return;
            await FormEl.validate(async (valid: boolean) => {
                if (!valid) return
                else {
                    // 没有编辑数据
                    const unChange = Object.is(JSON.stringify(rawData.value), JSON.stringify(editForm))
                    if (unChange) {
                        toast('数据未改动', 'info')

                        editDialogVisible.value = false

                        return;
                    }

                    editBtnLoading.value = true

                    // 每次提交编辑结果前 修改更新时间
                    updateTime.value = Random.now('A HH:mm:ss')
                    editForm.update_time = updateTime.value

                    const res = await service.request({
                        url: `/updateUser/${editForm.id}`,
                        method: "PUT",
                        data: {
                            ...editFormModel.value
                        },

                    })
                    if (res.data.status === 200) {
                        editDialogVisible.value = false

                        await getUserInfo()

                        toast(res.data.message)

                    } else {
                        editDialogVisible.value = false
                    }

                }
            }).finally(() => {
                editBtnLoading.value = false
            })
        }

        // 删除
        const handleDelete = (id: number) => {
            showModal('是否删除该用户', '温馨提示', "warning", "", true, true)
                .then(async () => {

                    const res = await service.request({
                        url: `/deleteUser/${id}`,
                        method: "DELETE",
                    })
                    if (res.data.status === 200) {
                        await getUserInfo()
                        toast(res.data.message)
                    }
                })
        }

        // 搜索
        const onReset = () => {
            for (const key of Object.keys(searchFormModel.value)) {
                searchFormModel.value[key] = ''
            }
        }
        const onSearch = async () => {
            if (!searchFormModel.value.keyword.trim()) return;
            const res = await service.request({
                url: `/query/${searchFormModel.value.keyword}`,
                method: "GET",
            })
            if (res.data.status === 200) {

                await getUserInfo()

                userInfo.value = res.data.data

                toast(res.data.message)

                onReset()
            } else {
                toast(res.data.message, 'error')

                onReset()
            }
        }

        // 更新状态
        const handleStateManagement = async (status: string, id: number) => {
            if (!status) return;

            if (status) {
                const res = await service.request({
                    url: `/updateStatus/${id}`,
                    method: 'PUT',
                    data: {
                        status: status === 'enabled',
                    }
                })
                if (res.status === 200) {
                    await getUserInfo()

                    toast(res.data.message)
                }
            }
        }

        // 分页
        const handlePageChange = (newPage: number) => {

            currentPage.value = newPage

            // 根据起始索引 和 结束索引获取当前页的数据                  [0, 9]     [10, 19]   [20, 29] ...
            const initIndex = pageSize * (newPage - 1) // 10 * (1-1) 10 * (2-1) 10 * (3-1) ...
            const endIndex = pageSize * newPage //        10 * 1      10 * 2     10 * 3 ...
            // 存放当前页的数据
            const CurrentPageData = []
            for (let i = initIndex; i < endIndex; i++) {
                if (userInfo.value[i]) CurrentPageData.push(userInfo.value[i])
            }
            currentTableData.value = CurrentPageData
        }
        watch(userInfo, (newVal) => {
            currentPage.value = 1

            totalCount.value = newVal.length

            currentTableData.value = userInfo.value.filter((_, index) => index < pageSize)
        })

        return {
            // 数据表格
            isLoading,
            userInfo,
            userAvatarSrcList,
            preAvatarSrcList,
            // 分页
            currentPage,
            pageSize,
            currentTableData,
            totalCount,
            // 编辑
            editDialogVisible,
            editIsFullscreen,
            editTooltipVisible,
            editFormRef,
            editFormModel,
            editFormRules,
            editBtnLoading,
            // 新增
            dialogVisible,
            addBtnLoading,
            isFullscreen,
            tooltipVisible,
            addFormRef,
            addFormModel,
            addFormRules,
            // 搜索
            searchFormModel,
            getUserInfo,
            handleAddSubmit,
            echoEditData,
            handleEditSubmit,
            handleDelete,
            onReset,
            onSearch,
            handleStateManagement,
            handlePageChange,
        }
    },
    {
        persist: {
            storage: sessionStorage,
        }
    }
)
